Skip to main content

Iterator Method

It provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. This pattern allows for traversing elements of a collection (like lists, sets, etc.) without needing to understand the details of the collection’s implementation.

Structure

  • Iterator Interface: Defines the methods for traversing elements.
  • Concrete Iterator: Implements the iterator interface to iterate over the collection.
  • Aggregate Interface: Defines a method to create an iterator.
  • Concrete Aggregate: Implements the aggregate interface to provide the appropriate iterator.
  • Client: Uses the iterator to traverse the collection.

Example

// Iterator Interface
interface Iterator {
boolean hasNext();
Object next();
}

// Aggregate Interface
interface BookCollection {
Iterator createIterator();
}

// Concrete Iterator for BookCollection
class BookIterator implements Iterator {
private Book[] books;
private int position;

public BookIterator(Book[] books) {
this.books = books;
this.position = 0;
}

@Override
public boolean hasNext() {
return position < books.length && books[position] != null;
}

@Override
public Object next() {
return hasNext() ? books[position++] : null;
}
}

// Concrete Aggregate
class Library implements BookCollection {
private Book[] books;
private int count;

public Library(int size) {
books = new Book[size];
count = 0;
}

public void addBook(Book book) {
if (count < books.length) {
books[count++] = book;
} else {
System.out.println("Library is full. Cannot add more books.");
}
}

@Override
public Iterator createIterator() {
return new BookIterator(books);
}
}

// Book class (the element)
class Book {
private String title;

public Book(String title) {
this.title = title;
}

public String getTitle() {
return title;
}
}

// Client code
public class Main {
public static void main(String[] args) {
Library library = new Library(5);
library.addBook(new Book("1984"));
library.addBook(new Book("To Kill a Mockingbird"));
library.addBook(new Book("The Great Gatsby"));

// Create an iterator for the library
Iterator iterator = library.createIterator();

// Traverse the collection
while (iterator.hasNext()) {
Book book = (Book) iterator.next();
System.out.println("Book Title: " + book.getTitle());
}
}
}